package com.originskyseed.platform.cms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.CmsAnchorRelateRecommend;
import com.originskyseed.platform.cms.model.ProductInfoTemplate;
import com.originskyseed.platform.cms.model.QrCode;
import com.originskyseed.platform.cms.service.ICmsAnchorRelateRecommendService;
import com.originskyseed.platform.cms.service.IProductInfoTemplateService;
import com.originskyseed.platform.cms.service.IQrCodeService;
import com.originskyseed.platform.cms.vo.request.CmsAnchorRelateRecommendRequestVO;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.common.utils.QRCodeUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.OrderNumberUtil;
import com.originskyseed.platform.task.service.ITaskRelateAssignPersonService;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 推荐主播信息表Controller类（OSI_ANCHOR_RELATE_RECOMMEND）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/cmsAnchorRelateRecommend")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class CmsAnchorRelateRecommendController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmsAnchorRelateRecommendController.class);

	@DubboReference
	private ICmsAnchorRelateRecommendService cmsAnchorRelateRecommendService;

	@DubboReference
	private ITaskRelateAssignPersonService taskRelateAssignPersonService;

	@DubboReference
	private IQrCodeService qrCodeService;

	@DubboReference
	private IProductInfoTemplateService productInfoTemplateService;

	/**
	 * 我的推荐主播_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsAnchorRelateRecommendList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CmsAnchorRelateRecommend>> cmsAnchorRelateRecommendList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CmsAnchorRelateRecommend>> result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			String tokenId=this.getParameterString("tokenId",null);
			// 请求对象
			CmsAnchorRelateRecommendRequestVO requestVO = this.getParameterBean(CmsAnchorRelateRecommendRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo == null || userInfo.getOtherAccount() == null || StringUtils.isEmpty(userInfo.getOtherAccount())) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.BUSINESS_BIND_ISNULL.getMsg()), null);
			}
			requestVO.setBusinessId(userInfo.getId());

			// 分页查询
			 BasePage<CmsAnchorRelateRecommend> page = new BasePage<CmsAnchorRelateRecommend>(requestVO.getPageNo(), requestVO.getPageSize());
			 page = this.cmsAnchorRelateRecommendService.selectListByPage(requestVO.toMap(), page, userInfo);
			 if(page!=null&&page.getTotalRecord()>0)
			 {
			 	List<CmsAnchorRelateRecommend> cmsAnchorRelateRecommendList0=page.getResults();
			 	List<String> anchorList=new ArrayList<>();
			 	for(int i=0;i<cmsAnchorRelateRecommendList0.size();i++)
				{
					String anchorId=cmsAnchorRelateRecommendList0.get(i).getAnchorId();
					if(anchorId!=null&&StringUtils.isNotBlank(anchorId)) {
						anchorList.add(cmsAnchorRelateRecommendList0.get(i).getAnchorId());
					}
				}
			 	if(anchorList!=null&&anchorList.size()>0) {
					// 请求接口
					TreeMap<String, Object> paramMap = new TreeMap<>();
					paramMap.put("productId", id);
					paramMap.put("channelId", userInfo.getOtherAccount());
					paramMap.put("anchorIds", String.join(",", anchorList));

					Map resultMap = QueryAppUtil.query("queryAnchorInfoByAppIdUrl", 1, paramMap);
					Integer code = Integer.parseInt(resultMap.get("code").toString());
					String msg = (String) resultMap.get("msg");
					if (code == 1) {
						// json字符串转jsonArray
						List<CmsAnchorRelateRecommend> cmsAnchorRelateRecommendList = new ArrayList<>();
						String data = (String) resultMap.get("data");
						cmsAnchorRelateRecommendList = JsonUtils.parseArray(data, CmsAnchorRelateRecommend.class);
						//createQrCode(userInfo, cmsAnchorRelateRecommendList, id,tokenId);
						page.setResults(cmsAnchorRelateRecommendList);
					} else {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), "") + "状态码：" + code + " msg: " + msg, null);
					}
				}
			 }
			result = new BaseResponseBody<BasePage<CmsAnchorRelateRecommend>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_ANCHOR_RELATE_RECOMMEND_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CmsAnchorRelateRecommend>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_ANCHOR_RELATE_RECOMMEND_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	private void createQrCode(UserInfo userInfo, List<CmsAnchorRelateRecommend> cmsAnchorRelateRecommendList, String productId,String tokenId) throws Exception {
		String userId = userInfo.getId();
		ProductInfoTemplate productInfoTemplate = productInfoTemplateService.selectProductInfoTemplateByUserId(userId);
		String path =productInfoTemplate==null?"":productInfoTemplate.getPath();

		if (cmsAnchorRelateRecommendList != null && cmsAnchorRelateRecommendList.size() > 0) {
			for (int i = 0; i < cmsAnchorRelateRecommendList.size(); i++) {
				CmsAnchorRelateRecommend cmsAnchorRelateRecommend = cmsAnchorRelateRecommendList.get(i);
				String inviteLink = cmsAnchorRelateRecommend.getInviteLink();

				cmsAnchorRelateRecommend.setImgPath(path);
				QrCode qrCode = new QrCode();
				qrCode.setDomainUrl(inviteLink);

				List<QrCode> qrCodeList = qrCodeService.selectList(qrCode);
				if (qrCodeList != null && qrCodeList.size() > 0) {
					cmsAnchorRelateRecommend.setQrCodePath(qrCodeList.get(0).getQrcodePath());
				} else {
					String anchorId = cmsAnchorRelateRecommend.getAnchorId();
					qrCode.setProductId(productId);
					qrCode.setAnchorId(anchorId);
					qrCode.setCreator(userInfo == null ? "" : userInfo.getName());
					qrCode.setCreatorId(userInfo == null ? "" : userInfo.getId());
					String number = OrderNumberUtil.makeOrderNum();
					String imgName = number + ".png";

					String filePath = "";
					try {
						filePath = QRCodeUtils.getQrcodeFilePath(inviteLink, imgName,tokenId);
					} catch (Exception ex) {
						logger.error(ex.getMessage());
					}
					if (filePath == null || StringUtils.isEmpty(filePath)) {
						continue;
					}
					cmsAnchorRelateRecommend.setQrCodePath(filePath);
					qrCode.setQrcodePath(filePath);
					qrCodeService.insertSelective(qrCode);
				}
			}
		}
	}

	/**
	 * 自定义分页
	 * 
	 * @param list
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	private List<CmsAnchorRelateRecommend> startPage(List<CmsAnchorRelateRecommend> list, Integer pageNum, Integer pageSize) {
		if (list == null) {
			return null;
		}
		if (list.size() == 0) {
			return null;
		}

		Integer count = list.size(); // 记录总数
		Integer pageCount = 0; // 页数
		if (count % pageSize == 0) {
			pageCount = count / pageSize;
		} else {
			pageCount = count / pageSize + 1;
		}

		int fromIndex = 0; // 开始索引
		int toIndex = 0; // 结束索引

		if (pageNum != pageCount) {
			fromIndex = (pageNum - 1) * pageSize;
			toIndex = fromIndex + pageSize;
		} else {
			fromIndex = (pageNum - 1) * pageSize;
			toIndex = count;
		}

		List<CmsAnchorRelateRecommend> pageList = list.subList(fromIndex, toIndex);

		return pageList;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsAnchorRelateRecommendSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<CmsAnchorRelateRecommend> cmsAnchorRelateRecommendSave(HttpServletRequest request) {
		BaseResponseBody<CmsAnchorRelateRecommend> result = null;
		try {
			// 请求对象
			CmsAnchorRelateRecommend cmsAnchorRelateRecommend = this.getParameterBean(CmsAnchorRelateRecommend.class);

			if (StringUtils.isNotBlank(cmsAnchorRelateRecommend.getId())) {
				this.cmsAnchorRelateRecommendService.updateByPrimaryKey(cmsAnchorRelateRecommend);
			} else {
				this.cmsAnchorRelateRecommendService.insertSelective(cmsAnchorRelateRecommend);
			}
			result = new BaseResponseBody<CmsAnchorRelateRecommend>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_CONTENT_SAVE_SUCCESS.getMsg()), cmsAnchorRelateRecommend);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsAnchorRelateRecommend>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_CONTENT_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 假删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsAnchorRelateRecommendDelete.json")
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> cmsAnchorRelateRecommendDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			for (String id : ids) {
				CmsAnchorRelateRecommend cmsAnchorRelateRecommend = this.cmsAnchorRelateRecommendService.selectByPrimaryKey(id);
				cmsAnchorRelateRecommend.getTaskId();
				// 完成人信息表需要做删除，逻辑待完善！

			}
			this.cmsAnchorRelateRecommendService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
